package la.ge.server.gs2ge;

import java.util.ArrayList;
import java.util.Collection;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;

import la.common.CommonException;
import la.common.xml.XMLHelper;
import la.ge.kml.KMLHelper;
import la.gs.GSResultRec;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 * Thead not safe
 * 
 * @author labile
 * 
 */
public class GSResultRecs2KMLNetLinks {

	private Element eNetLinkTemplate;

	private XPathExpression eNetLinkTemplateHref;

	private XPathExpression eNetLinkTemplateName;
	
	private Log logger = LogFactory.getLog( GSResultRecs2KMLNetLinks.class );

	public GSResultRecs2KMLNetLinks() {
		XMLHelper xmlHelper = new XMLHelper();
		XPath xPath = xmlHelper.createXMLPath();
		xPath.setNamespaceContext(KMLHelper.KML20XMLNSContext);
		eNetLinkTemplate = null;
		{
			Document doc2 = xmlHelper
					.sureLoadDocFromClassLoader("/la/ge/server/gs2ge/GSResultRecs2KMLNetLinks.xml");
			eNetLinkTemplate = doc2.getDocumentElement();
		}
		try {
			eNetLinkTemplateHref = xPath.compile("kml:Url/kml:href");
			eNetLinkTemplateName = xPath.compile("kml:name");
		} catch (XPathExpressionException e) {
			throw new RuntimeException(e);
		}
	}

	public Collection<Element> act(Collection<GSResultRec> gsResultSet, Document ownerDoc) {

		Collection<Element> result = new ArrayList<Element>();
		for (GSResultRec resultRec : gsResultSet) {
			try {
				Element eResultNetLink = (Element) eNetLinkTemplate.cloneNode(true);
				((Element) eNetLinkTemplateName.evaluate(eResultNetLink,
						XPathConstants.NODE)).setTextContent(resultRec.getTitle());

				Element eHref = (Element) eNetLinkTemplateHref.evaluate(
						eResultNetLink, XPathConstants.NODE);
				eHref.setTextContent(resultRec.getUrl());

				result.add((Element) ownerDoc.importNode(eResultNetLink, true));
			} catch (DOMException e) {
				logger.error( e, e );
			} catch (XPathExpressionException e) {
				logger.error( e, e );
			}
		}
		return result;
	}
}
